package com.sp.scmdb.serviceImpl;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sp.scmdb.bean.DepartmentBean;
import com.sp.scmdb.bean.UserBean;
import com.sp.scmdb.common.CommonParamter;
import com.sp.scmdb.dao.DepartmentDao;
import com.sp.scmdb.dao.EmployeeDao;
import com.sp.scmdb.dao.RoleDao;
import com.sp.scmdb.entity.Department;
import com.sp.scmdb.entity.Role;
import com.sp.scmdb.service.DepartmentService;
import com.sp.scmdb.service.LogService;

@Service("departmentService")
public class DepartmentServiceImpl implements DepartmentService {

	private DepartmentDao departmentDao;
	private EmployeeDao empDao;
	private LogService logs;
	private RoleDao roleDao;

	public void setRoleDao(RoleDao roleDao) {
		this.roleDao = roleDao;
	}

	@Required
	public void setLogs(LogService logs) {
		this.logs = logs;
	}

	public void setEmpDao(EmployeeDao empDao) {
		this.empDao = empDao;
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public List<Department> queryAll() {
		return departmentDao.queryAll();
	}

	@Transactional(readOnly = true)
	public List<Department> queryAll(UserBean user) {
		return departmentDao.queryAll(user);
	}

	@Transactional
	public String newDep(DepartmentBean t, UserBean user) {
		String result = "3";
		StringBuffer Hql = new StringBuffer("from Department where 1=1 ");
		if (StringUtils.isNotEmpty(t.getDeptName())) {
			Hql.append("and deptName='").append(t.getDeptName()).append("'");
			List<Department> list = departmentDao.queryHql(Hql.toString());
			if (CollectionUtils.isEmpty(list)) {
				Department department = new Department();
				department.setDeptName(t.getDeptName());
				departmentDao.save(department);
				logs.addLog(user, "添加 部门：\""+t.getDeptName()+"\"成功！");
				result = CommonParamter.CHECK_SUCCESS;
			} else {
				result = CommonParamter.CHECK_REPEAT;
			}
		}
		return result;
	}

	@Transactional
	public String editDep(DepartmentBean bean, UserBean user) {
		String result = "2";
		// 检查角色名称是否重复
		if (StringUtils.isNotEmpty(bean.getDeptName())) {
			StringBuffer Hql = new StringBuffer();
			Hql.append("from Department where id != " + bean.getId() + " and deptName = '" + bean.getDeptName() + "'");
			if (CollectionUtils.isEmpty(departmentDao.queryHql(Hql.toString()))) {
				Department department = departmentDao.getById(Integer.parseInt(bean.getId()));
				// 如果名称没有重复的
				department.setDeptName(bean.getDeptName());
				// 保存该角色
				departmentDao.update(department);
				logs.addLog(user, "修改 部门：\""+bean.getDeptName()+"\"成功！");
				result = CommonParamter.CHECK_SUCCESS;
			} else {
				result = CommonParamter.CHECK_REPEAT;
			}
		}
		return result;
	}

	@Transactional
	public String delDep(String[] ids, UserBean user) {
		String result = "1";
		Department department = null;
		for (int i = 0; i < ids.length; i++) {
			department = departmentDao.getById(Integer.parseInt(ids[i]));
			if (department != null) {
				// 如果人员表中有人员属于该部门，则不能删除
				if (!CollectionUtils.isEmpty(empDao.queryHql("from Employee where empDepID=" + department.getId()))){
					return "10";
				}
				// 日志
				logs.addLog(user, "删除 部门：\""+department.getDeptName()+"\"成功！");
				// 删除角色表中有关该部门的信息
				List<Role> listRole = roleDao.queryAll();
				String[] departments = null;
				StringBuffer resultDep = null;
				for (Role role : listRole) {
					if (StringUtils.isNotEmpty(role.getDepartment())) {
						// 角色部门不为空的时候，循环部门列表，并且从角色的部门列表中去掉当前删除的部门信息
						departments = role.getDepartment().split(",");
						resultDep = new StringBuffer();
						for (String dep : departments) {
							if (!dep.trim().equals(department.getId().toString())) {
								// 取出当前要删除的部门之外的部门，重新构造角色部门列表
								resultDep.append(dep + ",");
							}
						}
						if ("".equals(resultDep.toString().trim())){
							role.setDepartment("");
							roleDao.update(role);
						} else if (!role.getDepartment().equals(resultDep.substring(0, resultDep.length() - 1))) {
							// 如果之前的部门列表和现在部门列表不一样，则更新该角色的部门信息
							role.setDepartment(resultDep.substring(0, resultDep.length() - 1));
							roleDao.update(role);
						}
					}					
				}				
				
				// 删除部门信息
				departmentDao.delete(department);							
				
				result = CommonParamter.CHECK_SUCCESS;
			}
		}
		return result;
	}

	@Transactional(readOnly = true)
	public Department findID(String depId) {

		return departmentDao.getById(Integer.parseInt(depId));
	}

	@Transactional(readOnly = true)
	public List<Department> queryAllByHql(String hql) {
		return departmentDao.queryHql(hql);
	}
}
